package com.qf.springbootproject.user.controller;

import cn.hutool.jwt.JWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.springbootproject.config.Constants;
import com.qf.springbootproject.user.entity.Users;
import com.qf.springbootproject.user.mapper.UsersMapper;
import com.qf.springbootproject.user.service.UsersService;
import com.qf.springbootproject.utils.ResultVo;
import com.qf.springbootproject.user.vo.UserResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author yangyeqi
 * @since 2023-02-13
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UsersController {
    @Autowired
    UsersService usersService;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    UsersMapper usersMapper;

    @RequestMapping("/regist")
    public ResultVo register(@Valid @RequestBody UserResult userResult) {
        log.debug("参数为userResult={}", userResult);
        ResultVo resultVo = usersService.register(userResult.getUsername(), userResult.getPassword());
        return resultVo;
    }

    @RequestMapping("/login")
    public ResultVo login(String username, String password) throws JsonProcessingException {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        subject.login(usernamePasswordToken);
        Users user = (Users) subject.getPrincipal();
        //创建jwt token 并且把需要保存的数据放到token中
        //User对象---->json字符串
        ObjectMapper objectMapper = new ObjectMapper();//jackson类库提供的json转换器
        String userJson = objectMapper.writeValueAsString(user);
        String token = JWT.create().setPayload("sub", userJson)
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 14))
                .setIssuer("fmall")//token是由谁签发的
                .setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8))
                .sign();
        ResultVo ok = ResultVo.ok(user);
        //设置token到msg返回给前端
        ok.put("msg", token);
        return ok;
    }

}










